﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;

namespace XMLExport
{
    class SalesXMLExport
    {
        static void Main(string[] args)
        {

            CreateXml();
        }

        public static void CreateXml()
        {
            string fileName = "salesReport.xml";
            Encoding encoding = Encoding.GetEncoding("windows-1251");
            DateTime date = DateTime.Now;
            DateTime startDate = new DateTime(date.Year, date.Month, 1);
            DateTime endDate = new DateTime(date.Year, date.Month, DateTime.DaysInMonth(date.Year,date.Month));
            using (XmlTextWriter writer = new XmlTextWriter(fileName, encoding))
            {
                writer.Formatting = Formatting.Indented;
                writer.IndentChar = '\t';
                writer.Indentation = 1;
                writer.WriteStartDocument();
                writer.WriteStartElement("sales-report");
                writer.WriteAttributeString("start-date", startDate.Day + "/" + startDate.Month + "/" + startDate.Year);
                writer.WriteAttributeString("end-date", endDate.Day + "/" + endDate.Month + "/" + endDate.Year);
                BookstoreDataClassesDataContext context = new BookstoreDataClassesDataContext();
                var sales =
                    from s in context.Sales
                     join
                         b in context.Books on s.BookId equals b.BookId
                     where s.SaleDate >= startDate && s.SaleDate <= endDate
                     select new { ISBN = b.ISBN, Amount = s.Amount, Income = s.Amount * b.Price };
                   
                double totalIncomes = 0;
                foreach (var sale in sales)
                {
                    writer.WriteStartElement("book-sale");
                    writer.WriteStartElement("isbn");
                    writer.WriteString(sale.ISBN);
                    writer.WriteEndElement();
                    writer.WriteStartElement("amount");
                    writer.WriteString(sale.Amount.ToString());
                    writer.WriteEndElement();
                    writer.WriteStartElement("incomes");
                    writer.WriteString(sale.Income.ToString());
                    totalIncomes = totalIncomes + double.Parse(sale.Income.ToString());
                    writer.WriteEndElement();
                    writer.WriteEndElement(); 
                }
                writer.WriteStartElement("total-incomes");
                writer.WriteString(totalIncomes.ToString());
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteEndDocument();
            }

        }
    }
}
